package com.example.websockettest.webSocket.回收站;

import jdk.nashorn.internal.runtime.Version;
import org.apache.http.client.HttpClient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;


public class ChatGPTClient {

    private final String API_ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions";

    public String getResponse(String prompt) {

        try {
            URL url = new URL(API_ENDPOINT);
            Proxy  proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("n119.boom.skin", 7890));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer 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");

            String data = "{\"prompt\":\"" + prompt + "\",\"max_tokens\":100,\"n\":1,\"stop\":\"\"}";
            conn.setDoOutput(true);
            conn.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String output;
            StringBuilder sb = new StringBuilder();
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            conn.disconnect();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
